package com.yswee.mallnavi.parser;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.json.JSONArray;

import com.yswee.framework.data.BaseArrayData;
import com.yswee.mallnavi.entity.ArrayData;

public class BaseListGsonParser<T> extends BaseGsonParser<BaseArrayData<T>> {

	@Override
	public BaseArrayData<T> parseData(String json) {
		JSONArray ja = readListCode(json);
		if(mIsOk) {
			return parseData(ja);
		}
		return null;
	}
	
	public BaseArrayData<T> parseData(JSONArray ja) {
		if(ja != null) {
			T t = null; 
			ArrayData<T> array = new ArrayData<T>();
			for(int i = 0; i < ja.length(); i++) {
				try {
					t = parseDataT(ja.getJSONObject(i).toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(t != null) {
					array.array.add(t);
				}
			}
			return array;
		}
		return null;
	}
	
	protected T parseDataT(String json) {
		Class<T> cls = getDataTClassType();
		return mGson.fromJson(json, cls);
	}
	
	@SuppressWarnings("unchecked")
	protected Class<T> getDataTClassType() {
		Type genType = getClass().getGenericSuperclass();  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
		return (Class<T>) params[0]; 
	}
	
}
